import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { Product } from '../app/Product';
import { ProductService } from '../app/ProductService';
import { CartService } from '../app/CartService'

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.less'],
  providers: [ProductService, CartService]
})
export class ProductDetailComponent {
  product: Product | undefined
  products: Array<Product> = []

  constructor(private route: ActivatedRoute, private productService: ProductService, private cartService: CartService) {}

  ngOnInit() {
    // First get the product id from the current route.
    const routeParams = this.route.snapshot.paramMap;
    const productIdFromRoute = Number(routeParams.get('productId'));
    
    this.products = this.productService.getProducts()
    console.log("product-detail this.products", this.products);

    // Find the product that correspond with the id provided in route.
    this.product = this.products.find(product => product.id === productIdFromRoute);
    console.log("product-detail this.product", this.product);
  }

  addToCart(product: Product) {
    this.cartService.addToCart(product);
    window.alert('Your product has been added to the cart!');
    console.log(this.cartService.getItems());
  }
}
